package com.bigzero.workflow.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigzero.workflow.common.model.TokenAuthInfo;
import com.bigzero.workflow.modules.system.dao.UserRoleDao;
import com.bigzero.workflow.modules.system.entity.UserRoleEntity;
import com.bigzero.workflow.modules.system.service.UserRoleService;
import com.bigzero.workflow.modules.system.vo.MenuVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 用户关联角色实现类
 * @Author: fanxinxiong
 * @Date: 2025-02-14 14:48:00
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleDao, UserRoleEntity> implements UserRoleService{

    @Resource
    private UserRoleDao userRoleDao;

    /**
     * 查询菜单树形表格
     * @param tokenAuthInfo token认证信息
     * @param parentId 父id
     * @return List<MenuVo>
     */
    public List<MenuVo> getMenuVoTreeTableByTokenAuthInfo(TokenAuthInfo tokenAuthInfo, String parentId){
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("username", tokenAuthInfo.getUsername());
        map.put("type", 2);//菜单类型:1.目录,2.菜单,3.tab页,4.按钮,5.超链接,6.后台接口,7.其他
        List<MenuVo> voList = userRoleDao.selectMenuVoListMap(map);
        List<MenuVo> menuVoList = buildMenuVoTree(parentId, voList);
        return menuVoList;
    }

    /**
     * 根据map参数获取菜单vo集合
     * @param map map参数
     * @return List<MenuVo>
     */
    public List<MenuVo> getMenuVoListMap(HashMap<String, Object> map){
        return userRoleDao.selectMenuVoListMap(map);
    }

    /**
     * 根据集合构建树
     * @author: fanxinxiong
     * @date: 2024-02-13
     * @param parentId
     * @param menuVoList
     * @return List<MenuVo>
     */
    public List<MenuVo> buildMenuVoTree(String parentId, List<MenuVo> menuVoList){
        List<MenuVo> treeList = new ArrayList<MenuVo>();
        menuVoList.stream().forEach(vo->{
            if(parentId.equals(vo.getParentId())){
                treeList.add(findMenuVoChild(vo, menuVoList));
            }
        });
        return treeList;
    }

    /**
     * 查找子节点
     * @author: fanxinxiong
     * @date: 2025-02-14
     * @param menuVo
     * @param menuVoList
     * @return MenuVo
     */
    public MenuVo findMenuVoChild(MenuVo menuVo, List<MenuVo> menuVoList){
        menuVoList.stream().forEach(v ->{
            if(v.getParentId() != null && v.getParentId().equals(menuVo.getId())){
                if(menuVo.getChildren() == null){
                    menuVo.setChildren(new ArrayList<MenuVo>());
                }
                menuVo.getChildren().add(findMenuVoChild(v, menuVoList));
            }
        });
        return menuVo;
    }

}
